package com.polaris.live.ui.party.widget

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewTreeObserver
import android.widget.RelativeLayout
import com.blankj.utilcode.util.SnackbarUtils.dismiss
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.common.ext.dp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.databinding.PopupPartyUnlockBinding
import com.polaris.live.translation.R

/**
 * 输入密码
 * @author Created by 天晴 on 2024/3/9 17:36
 * @since 1.0.0
 **/
class EnterPasswordView(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) {
    val mBinding = PopupPartyUnlockBinding.inflate(LayoutInflater.from(context), this)
    private var onPasswordBack: (password: String) -> Unit = {}
    private var onClose: () -> Unit = {}
    private val mRect = Rect()
    private var mLastKeyboardHeight: Int = -1

    init {
        initListener()
    }

    fun setListener(passwordBack: (password: String) -> Unit, close: () -> Unit = {}) {
        this.onPasswordBack = passwordBack
        this.onClose = close
    }

    fun setUi(passwordError: Boolean) {
        mBinding.errorTips.text =
            if (passwordError) StringUtils.getString(R.string.password_error)
            else StringUtils.getString(R.string.party_password_tips)
        mBinding.passwordView.requestOneFocus()
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()

        rootView.viewTreeObserver.addOnGlobalLayoutListener(mOnGlobalLayoutListener)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()

        rootView.viewTreeObserver?.removeOnGlobalLayoutListener(mOnGlobalLayoutListener)
    }

    private val mOnGlobalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
        rootView.getWindowVisibleDisplayFrame(mRect)
        val keyboardHeight = rootView.height - mRect.bottom

        if (mLastKeyboardHeight != keyboardHeight) {
            ViewUtils.setMargin(
                this,
                bottomMargin = keyboardHeight - 1.dp
            )

            mLastKeyboardHeight = keyboardHeight
        }
    }

    fun onDismiss() {
        mBinding.passwordView.clearText()
    }

    private fun initListener() {
        mBinding.apply {
            confirm.setOnSingleClickListener {
                passwordView.getText()?.let {
                    onPasswordBack.invoke(it)
                    dismiss()
                } ?: ToastGravity.showGravity(R.string.password_error)
            }
            cancel.setOnSingleClickListener {
                dismiss()
                onClose.invoke()
            }
        }

    }

}